package com.tongji.quickCRUDQ.dao.jdbc;

import java.util.Map;

import com.tongji.quickCRUDQ.webapp.QueryParam;

public class SqlserverPagination implements Pagination {
	/* (non-Javadoc)
	 * @see com.tongji.quickCRUDQ.dao.jdbc.Pagination#formatPageSQL(com.tongji.quickCRUDQ.dao.jdbc.QueryParam)
	 */
	public String formatPageSQL(String sql, QueryParam queryParam) {
		StringBuffer pageSql=new StringBuffer();
		int max=queryParam.getRowsOfPage()*queryParam.getPageNo();
		int min=max-queryParam.getRowsOfPage();
		sql=sql.trim().substring(6);
		pageSql.append("select * from (\n select top ").append(max).append(" ")
		       .append(sql).append("\n) table_max@sql where not exists(\n")
		       .append("  select * from (\n     select top ").append(min).append(" ")
		       .append(sql).append("\n  ) table_min@sql where id=table_max@sql.id \n) ")
		       .append(queryParam.getOrderby());
		return pageSql.toString();
	}

	/* (non-Javadoc)
	 * @see com.tongji.quickCRUDQ.dao.jdbc.Pagination#formatCountSQL(java.lang.String)
	 */
	public String formatCountSQL(String sql) {
		StringBuffer countSql=new StringBuffer();
		sql=sql.trim().substring(6);
		
		countSql.append("select count(*) cnt from (\n select top ").append(Integer.MAX_VALUE).append(" ")
		        .append(sql).append("\n) tableCnt@sql");
		return countSql.toString();
	}  

	/* (non-Javadoc)
	 * @see com.tongji.quickCRUDQ.dao.jdbc.Pagination#formatRownumSQL(java.lang.String, java.lang.String)
	 */
	public String formatRownumSQL(String sql, String id, CommonDao commonDao) {
		StringBuffer rownumSql=new StringBuffer();
		sql=sql.trim().substring(6);
        sql="select  top "+Integer.MAX_VALUE+" "+sql;  
//        sql=StringUtil.replaceAll(sql, "'", "''");
        Map map=commonDao.callProcedure("P_ROWNUM", new int[]{1,1,0}, new String[]{sql,id,"0"});
        String s=(String)map.get("param3");
		rownumSql.append("select ").append(s).append(" RWNM");
		
		return rownumSql.toString();
	}
}
